package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final String KEY_PREFIX_CODE = "ly:sms:phone:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Boolean exists(String data, Integer type) {

        // 只能为1或则2   为2时候是手机号要校验
        if (type !=1 && type != 2 || StringUtils.isBlank(data) || (type == 2 && !RegexUtils.isPhone(data))){
            throw new LyException(400,"请求参数有误");
        }
        //
        return this.query()
                .eq(type == 1,"username",data)
                .eq(type == 2,"phone",data)
                .count() == 1;
    }

    @Override
    public void sendSms(String phone) {

        // 1.验证手机号格式
        if (!RegexUtils.isPhone(phone)){
            throw new LyException(400, "手机号格式不正确");
        }
        // 2.使用Apache的工具类生成6位数字验证码
        String code = RandomStringUtils.randomNumeric(6);
        // 3.保存验证码到redis
        redisTemplate.opsForValue().set(KEY_PREFIX_CODE + phone,code,5L, TimeUnit.MINUTES);
        //4.发送rabitMQ消息到ly-sms
        Map<String,String> msg = new HashMap<>();
        msg.put("phone",phone);
        msg.put("code",code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,msg);
    }

    @Override
    @Transactional
    public void register(User user, String code) {

        // 1.校验验证码
        if (StringUtils.isBlank(code)){
            throw new LyException(400,"验证码不能为空");
        }
        // 1.1 取出redis中的验证码
        String key = KEY_PREFIX_CODE + user.getPhone();
        System.out.println("key = " + key);
        if (!redisTemplate.hasKey(key)){
            throw new LyException(400,"验证码过期，请重新发送");
        }
        String cacheCode = redisTemplate.opsForValue().get(key);
        System.out.println("cacheCode = " + cacheCode);
        if (!StringUtils.equals(code,cacheCode)){
            throw new LyException(400,"验证码不正确");
        }
        // 2.对密码进行加密，md5加盐加密，盐值在算法中，每一次的盐值都不相同
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        //先根据密文推算出盐值，然后明文+盐值，加密，再次比较新密文和密文
        //passwordEncoder.matches("明文","密文");
        // 3.写入数据库
        this.save(user);

    }

    @Override
    public UserDTO queryUserByPhoneAndPassword(String username, String password) {

        // 1.根据用户名查询
        User user = this.query().eq("username", username).one();
        if (null == user){
            throw new LyException(400,"用户名或密码错误");
        }
        //2.校验密码  先根据密文推算出盐值，然后明文+盐值，加密，再次比较新密文和密文
        if (!passwordEncoder.matches(password,user.getPassword())){
            throw new LyException(400,"用户名或密码错误");
        }
        return new UserDTO(user);
    }

    @Override
    public UserDetail queryUser() {
        return UserContext.getUser();
    }
//    @Override
//    public UserDetail queryUser(String token) {
//        UserDetail userDetail = null;
//        try {
//            Payload payload = jwtUtils.parseJwt(token);
//            userDetail = payload.getUserDetail();
//        } catch (Exception e) {
//            throw new LyException(401,"用户未登录");
//        }
//
//        return userDetail;
//    }
}
